import fnmatch
import os

def ensure_dir(f):
    d = os.path.dirname(f)
    if not os.path.exists(d):
        os.makedirs(d)
        
template = '{\n    "id": "{ID}",\n    "source": "{PATH}",\n    "width": {WIDTH},\n    "height": {HEIGHT},\n    "offset_x": 0,\n    "offset_y": 0\n}'

outdir = 'files/'
ensure_dir(outdir + 'sprites/')
ensure_dir(outdir + 'maps/')

terrainIdx = 0
f_terr = open(outdir + 'maps/terrain.json', 'w')
f_terr.write('{\n    "0": "blank"')
f_list = open(outdir + 'sprites/_spriteList.json', 'w')
f_list.write('{\n    "sprites": [')

root = '..\\..\\..\\img\\terrain\\'
for (r, _, files) in os.walk(root):
    for file in files:
        if fnmatch.fnmatch(file, '*.png'):
            fn = 'terrain/' + r[root.__len__():].replace('\\', '/') + '/' + file
            f = open(outdir + 'sprites/' + file[0:-3] + 'json', 'w')
            f.write(template.replace('{ID}', file[0:-4]).replace('{PATH}', fn).replace('{WIDTH}', '16').replace('{HEIGHT}', '16'))
            f_list.write((',' if terrainIdx > 0 else '') + '\n        "sprites/' + file[0:-3] + 'json"')
            terrainIdx+=1
            f_terr.write(',\n    "' + str(terrainIdx) + '": "' + file[0:-4] + '"')
            f.close()
f_terr.write('\n}')
f_terr.close()
f_list.write('\n    ]\n}')
f_list.close()